package com.lbjhan.rpc.serializer;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.lbjhan.rpc.pojo.User;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class HessianSerializer<T> implements ISerializer {
    @Override
    public byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream);
        hessian2Output.writeObject(obj);
        hessian2Output.getBytesOutputStream().flush();
        hessian2Output.completeMessage();
        hessian2Output.close();
        return byteArrayOutputStream.toByteArray();
    }

    @Override
    public T deserialize(byte[] bytes, Class clazz) throws IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        Hessian2Input hessian2Input = new Hessian2Input(byteArrayInputStream);
        T t = (T)hessian2Input.readObject();
        return t;
    }

    public static void main(String[] args) throws IOException {
        HessianSerializer<User> userHessianSerializer = new HessianSerializer<>();
        byte[] bytes = userHessianSerializer.serialize(new User(1, "tom"));
        System.out.println(bytes.length);
        User user = userHessianSerializer.deserialize(bytes, null);
        System.out.println(user);
        /**
         * 45
         * User(id=1, name=tom)
         */
    }
}
